package login

import (
	"errors"
	"public_security/controllers"
	"public_security/databases"
	"public_security/models"
	"public_security/tools"
)

func Login(ctrl *controllers.BaseController, req *models.Users) (*models.Users, error) {
	user := new(models.Users)
	databases.DbDefault.Model(user).Where("account=?", req.Account).First(&user)
	if user == nil {
		return nil, errors.New("用户不存在")
	}
	if user.Password != models.SignMD5Up(req.Password) {
		return nil, errors.New("密码错误")
	}
	token := GetToken(user)
	user.Token = token
	databases.DbDefault.Model(user).Where("id=?", user.Id).Update("token", user.Token)
	models.AttachTokenToCookies(user, ctrl.Ctx)
	return user, nil
}

func GetToken(i *models.Users) string {
	auth := tools.NewAuthTool()
	token := auth.GenToken(map[string]interface{}{
		"id":        i.Id,
		"loginType": "user",
	})
	return token
}
